<template>
  <div class="aside-operate">
    <ul class="operate-box" v-if="operateList.length">
      <template v-for="(item, index) in operateList">
        <li
          class="operate-item flex-wrap flex-center-wrap flex-column-wrap"
          v-if="item.isShow"
          :key="index"
          @click="handleClick(item, 'click')"
          @mouseenter="handleClick(item, 'hover')"
          @mouseleave="handleClick(item, 'hover')"
        >
          <zl-icon
            :icon="
              item.active || item.hoverActive ? item.activeIcon : item.icon
            "
            :icon-style="iconStyle"
          ></zl-icon>
          <span
            class="operate-title"
            :style="{ color: item.active ? '#3480ff' : '#666666' }"
          >
            {{ item.title }}
          </span>
          <div
            v-if="item.children && item.children.length && item.isShowChildren"
            class="share-box flex-wrap"
          >
            <div
              @click.stop="handleClick(child, 'click')"
              @mouseenter="handleClick(child, 'hover')"
              @mouseleave="handleClick(child, 'hover')"
              class="share-item flex-column-wrap flex-center-wrap"
              v-for="(child, index) in item.children"
              :key="index"
            >
              <zl-icon
                :icon="child.active ? child.activeIcon : child.icon"
                :icon-style="iconStyle"
              ></zl-icon>
              <span :style="{ color: child.active ? '#3480ff' : '#666666' }">
                {{ child.title }}
              </span>
            </div>
          </div>
        </li>
      </template>
      <el-dialog
        class="wx-code-dialog-box"
        custom-class="wx-code-dialog"
        :visible="isShowWxDialog"
        @close="isShowWxDialog = false"
        :append-to-body="false"
        width="296px"
      >
        <div class="wxCode-box flex-center-wrap flex-column-wrap">
          <div class="wxCode-title">扫码分享至微信</div>
          <div class="wxCode-text">
            打开微信“扫一扫”，打开网页后点击屏幕右上角分享按钮
          </div>
          <div class="wxCode"></div>
        </div>
      </el-dialog>
    </ul>
    <el-dialog
      class="pdf-prev-dialog"
      :visible="isShowDownUrl"
      :append-to-body="false"
      :show-close="false"
      width="605px"
    >
      <canvas id="pdf-box" class="pdf-prev-box" width="430"></canvas>
      <div slot="footer" class="flex-center">
        <div class="login-btn" @click="goToLogin">登录下载</div>
        <div class="cancle-btn" @click="isShowDownUrl = false">取消</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  postCollectionArticle,
  postXCancleCollectionArticle,
  getCollectionStatus,
  getArtLike,
  postArtLike,
  postCancleArtLike,
  getCounts
} from '@/api/information_detail'

import zlIcon from '@/components/zlIcon.vue'
export default {
  components: {
    zlIcon
  },
  props: {
    articleDetail: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      operateList: [
        {
          title: '点赞',
          icon: 'icon-dianzan1-copy',
          activeIcon: 'icon-dianzan1',
          clickType: 1,
          isShow: true,
          callback: {
            click: this.handleThumbs,
            hover: item => {
              item.hoverActive = !item.hoverActive
            }
          },
          active: false,
          hoverActive: false
        },
        {
          title: '收藏',
          icon: 'icon-shoucang-copy',
          activeIcon: 'icon-shoucang',
          clickType: 2,
          isShow: true,
          callback: {
            click: this.handleCollection,
            hover: item => {
              item.hoverActive = !item.hoverActive
            }
          },
          active: false,
          hoverActive: false
        },
        {
          title: '下载',
          icon: 'icon-xiazai-copy',
          activeIcon: 'icon-xiazai',
          clickType: 3,
          isShow: true,
          callback: {
            click: this.handleDownload,
            hover: item => {
              item.active = !item.active
            }
          },
          active: false
        },
        {
          title: '分享',
          icon: 'icon-fenxiang-copy',
          activeIcon: 'icon-fenxiang',
          clickType: 4,
          isShow: true,
          callback: {
            click: () => {},
            hover: this.handleShare
          },
          active: false,
          isShowChildren: false,
          children: [
            {
              title: '微博',
              icon: 'icon-weibo-copy',
              activeIcon: 'icon-weibo',
              active: false,
              type: '1',
              callback: {
                click: this.shareWeibo,
                hover: item => {
                  item.active = !item.active
                }
              }
            },
            {
              title: '微信',
              icon: 'icon-weixin-copy',
              activeIcon: 'icon-weixin',
              active: false,
              type: '1',
              callback: {
                click: this.shareWeixin,
                hover: item => {
                  item.active = !item.active
                }
              }
            },
            {
              title: 'QQ',
              icon: 'icon-qq-copy',
              activeIcon: 'icon-qq',
              active: false,
              type: '1',
              callback: {
                click: this.shareQQ,
                hover: item => {
                  item.active = !item.active
                }
              }
            }
          ]
        },
        {
          title: '回到顶部',
          icon: 'icon-zhiding-copy',
          activeIcon: 'icon-zhiding',
          clickType: 5,
          isShow: true,
          callback: {
            click: this.handleToTop,
            hover: item => {
              item.active = !item.active
            }
          },
          active: false
        }
      ],
      iconStyle: {
        width: '32px',
        height: '32px',
        verticalAlign: 'middle'
      },
      zlaBtn: {
        key_name: '',
        key_content: ''
      },
      // 是否显示资料预览弹窗
      isShowDownUrl: false,
      // 是否展示微信弹窗
      isShowWxDialog: false,
      //当前下载的专业
      professionName: ''
    }
  },
  computed: {
    // down_url(){
    //   this.$forceUpdate()
    //   return this.articleDetail&&this.articleDetail.down_url||''
    // }
    isLogin() {
      return this.$store.state.user.isLogin
    }
  },
  methods: {
    // 点赞收藏等数量统计
    async getCounts(params) {
      getCounts({ ...params, id: this.articleDetail.id })
    },
    handleClick(item, type) {
      if (type === 'click') {
        this.zlaBtn = {
          key_name: item.title,
          key_content: item.title + '_' + this.articleDetail.topic
        }
      }
      if (+item.clickType === 5) {
        //回到顶部
        item.callback[type](item)
        return
      }
      let isPdfFile = false
      if (this.down_url) {
        let index = this.down_url.split('/').length - 1
        isPdfFile = this.down_url.split('/')[index].includes('.pdf')
          ? true
          : false
      }
      if (
        !this.isLogin &&
        type === 'click' &&
        (+item.clickType !== 3 ||
          (+item.clickType === 3 && this.down_url && !isPdfFile))
      ) {
        // 点赞，存入缓存
        if (item.clickType === 1) {
          sessionStorage.setItem('dianzan_id', this.articleDetail.id)
        }
        // 收藏，存入缓存
        if (item.clickType === 2) {
          sessionStorage.setItem('shoucang_id', this.articleDetail.id)
        }
        this.showLoginDialog()
        return
      } else if (
        !this.isLogin &&
        type === 'click' &&
        +item.clickType === 3 &&
        this.down_url &&
        isPdfFile
      ) {
        // 未登录、是点击下载、有down_url并且资源是pdf资源 显示资料预览弹窗
        this.dynamicLoadJs(
          '//image.zlketang.com/public/news/js/components/pdf2canvas/pdf.2.0.943.min.js',
          'pdfjs',
          this.prevPdf
        )
        this.isShowDownUrl = true
        return
      }
      item.callback[type](item)
    },
    // 控制点赞
    async handleThumbs(item) {
      if (item.active) {
        //已点赞 取消点赞
        let params = { news_id: this.articleDetail.id }
        let res = await postCancleArtLike(params).catch(err => {
          return { errcode: 404, errmsg: '网络错误请重试' }
        })
        if (+res.errcode === 0) {
          item.active = !item.active
          this.$message({ type: 'success', message: '取消点赞成功' })
          let zanParams = { zan_count: -1 }
          this.getCounts(zanParams)
        } else {
          this.$message({ type: 'warning', message: res.errmsg })
        }
      } else {
        //未点赞，点赞
        let params = { news_id: this.articleDetail.id }
        let res = await postArtLike(params).catch(err => {
          return { errcode: 404, errmsg: '网络错误请重试' }
        })
        if (+res.errcode === 0) {
          item.active = !item.active
          this.$message({ type: 'success', message: '点赞成功' })
          let zanParams = { zan_count: 1 }
          this.getCounts(zanParams)
        } else {
          this.$message({ type: 'warning', message: res.errmsg })
        }
      }
    },
    // 收藏
    async handleCollection(item) {
      if (item.active) {
        //已收藏 取消收藏
        //未收藏，收藏
        let params = { news_id: this.articleDetail.id }
        let { errcode, errmsg } = await postXCancleCollectionArticle(
          params
        ).catch(err => {
          return { errcode: 404, errmesg: '网络错误,请重试' }
        })
        if (+errcode === 0) {
          this.$message({ type: 'success', message: '取消收藏成功' })
          item.active = !item.active
          let collectParams = { collect_count: -1 }
          this.getCounts(collectParams)
        } else {
          this.$message({ type: 'warning', message: errmsg })
        }
      } else {
        //未收藏，收藏
        let params = { news_id: this.articleDetail.id }
        let { errcode, errmsg } = await postCollectionArticle(params).catch(
          err => {
            return { errcode: 404, errmesg: '网络错误,请重试' }
          }
        )
        if (+errcode === 0) {
          this.$message({ type: 'success', message: '收藏成功' })
          item.active = !item.active
          let collectParams = { collect_count: 1 }
          this.getCounts(collectParams)
        } else {
          this.$message({ type: 'warning', message: errmsg })
        }
      }
    },
    // 登录下载，跳转到登录页
    goToLogin() {
      this.zlaBtn = {
        key_name: '登录下载',
        key_content: this.professionName
      }
      this.professionId
      sessionStorage.setItem('download_id', this.articleDetail.id)
      sessionStorage.setItem('lastUrl', location.href)
      this.goTo('/login.html', {
        query: {},
        watch: true
      })
    },
    // 下载
    handleDownload(item) {
      item.active = !item.active
      window.open(this.down_url)
    },
    // 分享
    handleShare(item, type) {
      item.active = !item.active
      item.isShowChildren = !item.isShowChildren
    },
    // 分享到微博
    shareWeibo() {
      let params = { share_weibo_count: 1 }
      this.getCounts(params)
      var p = {
        url: location.href,
        appkey: '',
        pic: this.articleDetail.headimg,
        title: this.articleDetail.topic || this.articleDetail.title,
        code: 'utf-8'
      }
      var s = []
      for (var i in p) {
        s.push(i + '=' + encodeURIComponent(p[i] || ''))
      }
      var src = 'http://service.weibo.com/share/share.php?' + s.join('&')
      window.open(src)
    },
    // 分享到微信
    shareWeixin(e) {
      this.isShowWxDialog = true
      let params = { share_wx_count: 1 }
      this.getCounts(params)
      // 如果已生成过二维码，则不在生成
      this.$nextTick(() => {
        if ($('.wxCode').children().length > 0) return
        $('.wxCode').qrcode({
          text: location.href, //设置二维码内容
          render: 'canvas', //设置渲染方式
          width: 200, //设置宽度,默认生成的二维码大小是 256×256
          height: 200, //设置高度
          typeNumber: -1, //计算模式
          background: '#ffffff', //背景颜色
          correctLevel: 0,
          foreground: '#000000' //前景颜色
        })
      })
    },
    // 分享到qq
    shareQQ() {
      let params = { share_qq_count: 1 }
      this.getCounts(params)
      var p = {
        url: location.href,
        title: this.articleDetail.topic || this.articleDetail.title,
        summary: this.articleDetail.briefing,
        pics: this.articleDetail.headimg,
        width: '32',
        height: '32'
      }
      var s = []
      for (var i in p) {
        s.push(i + '=' + encodeURIComponent(p[i] || ''))
      }
      var src =
        'https://connect.qq.com/widget/shareqq/index.html?' + s.join('&')
      window.open(src)
    },
    // 回到顶部
    handleToTop(item) {
      document.documentElement.scrollTop = 0
    },
    // setLeft() {
    //   let dom = document.querySelector('.operate-box')
    //   let clientWidth = document.documentElement.clientWidth
    //   dom.style.left = clientWidth < 1200 ? '0px' : (((clientWidth - 1200) / 2) * 276) / 390 + 'px'
    // },
    // 之了数据点击
    sendZlaClick() {
      this.keyClick({
        ...this.zlaBtn
      })
    },

    // 预览pdf方法
    prevPdf() {
      let url = this.down_url
      let id = 'pdf-box'
      // 将文件路径改为跟随协议
      url = url.replace(/http\:|https\:/g, '')
      pdfjsLib.GlobalWorkerOptions.workerSrc =
        '//image.zlketang.com/public/news/js/components/pdf2canvas/pdf.worker.2.0.943.min.js'
      var loadingTask = pdfjsLib.getDocument({ url: url }) //  _url为后台请求pdf流的路径
      loadingTask.promise.then(function(pdf) {
        pdf.getPage(1).then(function(page) {
          var scale = 1.5
          var viewport = page.getViewport(scale)
          var canvas = document.getElementById(id)
          var context = canvas.getContext('2d')
          canvas.height = viewport.height
          canvas.width = viewport.width
          var renderContext = {
            canvasContext: context,
            viewport: viewport
          }
          page.render(renderContext)
        })
      })
    }
  },

  mounted() {
    let { meta, path } = this.$route
    let { profession_name } = meta
    this.professionName = profession_name || '初级会计职称'
    // this.setLeft()
    // window.onresize = this.setLeft
    // window.onload = this.setLeft
    this.storage.init()
    this.dynamicLoadJs(
      '//image.zlketang.com/public/news/js/jquery.qrcode.min.js',
      'jqueryQrcode'
    )
    let download_id = sessionStorage.getItem('download_id')
    if (download_id && this.isLogin) {
      this.handleDownload()
      sessionStorage.removeItem('download_id')
    }
  },
  watch: {
    zlaBtn: {
      handler() {
        this.sendZlaClick()
      },
      deep: true
    },
    articleDetail: {
      handler(data) {
        if (data.id && data.down_url) {
          //判断改资讯是否是存在资料下载
          this.down_url = data.down_url
          this.operateList[2].isShow = true
        } else {
          this.operateList[2].isShow = false
        }
        if (this.isLogin) {
          //获取点赞和收藏信息
          let params = { news_id: data.id }
          getCollectionStatus(params)
            .then(res => {
              let {
                data: { is_collection },
                errcode
              } = res
              if (+errcode === 0) {
                this.operateList[1].active = is_collection
                let shoucang_id = sessionStorage.getItem('shoucang_id')
                if (!shoucang_id) return
                if (!is_collection) {
                  //如果已经收藏过，不再执行收藏操作,没有则执行收藏
                  let item = this.operateList[1]
                  this.handleCollection(item)
                  sessionStorage.removeItem('shoucang_id')
                } else {
                  this.$message({ type: 'success', message: '收藏成功' })
                  sessionStorage.removeItem('shoucang_id')
                }
              }
            })
            .catch(err => {
              this.$message({ type: 'warning', message: '网络错误请重试' })
            })
          getArtLike(params)
            .then(res => {
              let {
                data: { like },
                errcode
              } = res
              if (+errcode === 0) {
                this.operateList[0].active = like === 0 ? false : true
                let dianzan_id = sessionStorage.getItem('dianzan_id')
                if (!dianzan_id) return
                if (!like) {
                  //如果已经点赞过，不再执行点赞操作,没有则执行点赞
                  let item = this.operateList[0]
                  this.handleThumbs(item)
                  sessionStorage.removeItem('dianzan_id')
                } else {
                  this.$message({ type: 'success', message: '点赞成功' })
                  sessionStorage.removeItem('dianzan_id')
                }
              }
            })
            .catch(err => {
              this.$message({ type: 'warning', message: '网络错误请重试' })
            })
        }
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
.operate-box {
  padding: 10px 0;
  position: fixed;
  left: 276px;
  top: 280px;
  background: #ffffff;
  border-radius: 12px;
  z-index: 2022;
}
@media screen and (max-width: 1900px) {
  .operate-box {
    left: 40px;
  }
}
.operate-item {
  position: relative;
  margin-top: 16px;
  width: 64px;
  cursor: pointer;
}
.operate-item:first-of-type {
  margin-top: 0;
}
.operate-title {
  margin-top: 3px;
  font-size: 12px;
  font-weight: 400;
  color: #666666;
  line-height: 17px;
}
.operate-title-active {
  /* css-ignore */
  color: #3480ff;
}
.share-box {
  position: absolute;
  left: 64px;
  top: -10px;
  z-index: 10;
  background-color: #fff;
  overflow: hidden;
  width: 222px;
  height: 68px;
  border-radius: 0 8px 8px 0;
}
.share-item {
  cursor: pointer;
  margin-left: 10px;
  padding: 6px 16px;
  background-color: #fff;
}
.share-item:first-of-type {
  margin-left: 0;
  padding-left: 10px;
}
.wxCode-box {
  /* css-ignore */
  padding: 30px 30px 50px 30px;
  background-color: white;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.2);
  line-height: 1.6em;
  border-radius: 12px;
}

.wxCode-title {
  /* css-ignore */
  text-align: center;
  font-size: 20px;
  color: #262626;
  line-height: 28px;
  font-weight: bold;
}

.wxCode-text {
  /* css-ignore */
  margin-top: 10px;
  font-size: 16px;
  font-weight: 400;
  color: #8c8c8c;
  line-height: 22px;
}
.wxCode {
  /* css-ignore */
  margin-top: 30px;
  display: inline-block;
  width: 200px;
  height: 200px;
}
.pdf-prev-box {
  max-height: 700px;
  overflow: auto;
  border: 1px solid #edeef0;
}
.aside-operate /deep/ .pdf-prev-dialog .el-dialog__header {
  padding: 10px 26px 16px;
}
.aside-operate /deep/ .pdf-prev-dialog .el-dialog__body {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: none;
}
.login-btn {
  width: 140px;
  height: 40px;
  background: #3480ff;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 400;
  color: #ffffff;
  line-height: 40px;
  text-align: center;
}
.cancle-btn {
  margin-left: 30px;
  width: 140px;
  height: 40px;
  background: #f0f1f2;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 400;
  color: #9fa6b3;
  line-height: 40px;
  text-align: center;
}
.aside-operate /deep/.wx-code-dialog-box .el-dialog {
  border-radius: 12px;
}
.aside-operate /deep/ .wx-code-dialog .el-dialog__header {
  padding: 0;
}
.aside-operate /deep/ .wx-code-dialog .el-dialog__body {
  padding: 0;
}
/* .width-active-enter,
.width-active-leave-to {
  width: 0px;
}
.width-active-enter-active,
.width-active-leave-active {
  transition: width 0.3s ease;
} */
</style>
